package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"gitee.com/law-api/conf"
	"gitee.com/law-api/routers"
)

type KeyTester struct {
	url     string
	keyFile *os.File
	quit    chan struct{}
}

func NewKeyTester(config *conf.TesterConf) *KeyTester {
	var router = "/api/add/address"
	t := &KeyTester{
		url:     config.ServerURL() + router,
		keyFile: config.KeyFile(),
		quit:    make(chan struct{}),
	}

	return t
}

//Close shutdown its test loop
func (kt *KeyTester) Close() {
	close(kt.quit)
}

func (kt *KeyTester) Do(times int) {
	var request = []byte("123")

	result := make(chan *routers.KeyResponse, times)

	for i := 0; i < times; i++ {
		go func() {
			res, err := kt.sendData(request)
			if err != nil {
				log.Printf("send err: %v", err)
			}
			result <- res
		}()
	}

	var succeed = 0
	for i := 0; i < times; i++ {
		res := <-result
		if res == nil {
			continue
		}
		if res.Code != 0 {
			continue
		}
		if res.Data == nil {
			continue
		}
		succeed++
		//storage key
		kt.SaveKeyFile(res.Data.Privkey)
	}
	log.Printf("send key Request! total: %v, succeed: %v\n", times, succeed)

}
func (kt *KeyTester) sendData(data []byte) (*routers.KeyResponse, error) {
	r, err := http.Post(kt.url, "application/json;charset=utf-8", bytes.NewBuffer(data))
	if err != nil {
		log.Printf("send http err: %v\n", err)
		return nil, err
	}
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Printf("read http err: %v\n", err)
		return nil, err
	}
	defer r.Body.Close()

	res := new(routers.KeyResponse)
	if err = json.Unmarshal(b, res); err != nil {
		fmt.Printf("json parse err: %v\n", err)
		return nil, err
	}
	return res, nil
}

func (kt *KeyTester) SaveKeyFile(key string) {
	kt.keyFile.WriteString(key + "\n")
}
